package com.blockmeta.bbs.baselibrary.utils;

import androidx.annotation.NonNull;
import android.text.TextUtils;

import com.blockmeta.bbs.baselibrary.R;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author AirThor
 * @date 2019/6/18.
 */
public class FormatUtil {
    /**
     * 科学技术法转String
     *
     * @param notation
     * @return
     */
    public static String notation2String(String notation) {
        BigDecimal bd = null;
        try {
            bd = new BigDecimal(notation);
            return bd.toPlainString();
        } catch (Exception e) {
            return "1";
        }
    }

    public static String notation2StringPercent(String notation) {
        BigDecimal bd = null;
        try {
            bd = new BigDecimal(notation);
            BigDecimal bd100 = new BigDecimal("100");
            NumberFormat nf = NumberFormat.getInstance();
            return nf.format(bd.multiply(bd100)) + "%";
        } catch (Exception e) {
            return "1";
        }
    }

    /**
     * 美元转人民币保留两位
     *
     * @param money
     * @return
     */
    public static String usd2cny(String money, Double rate) {
        String notation2String = notation2String(money);
        double money2 = Double.parseDouble(notation2String) * rate;
        DecimalFormat df;
        if (money2 >= 1) {
            df = new DecimalFormat("0.00");
        } else {
            df = new DecimalFormat("0.0000");
        }
        return df.format(money2);
    }

    public static String usd2cny(String money, Float rate) {
        String notation2String = notation2String(money);
        double money2 = Double.parseDouble(notation2String) * rate;
        DecimalFormat df;
        if (money2 >= 1) {
            df = new DecimalFormat("0.00");
        } else {
            df = new DecimalFormat("0.0000");
        }
        return df.format(money2);
    }

    public static String cny2usd(Double money, Double rate) {
            double money2 = CalculateUtil.div(money,rate);
            DecimalFormat df;
            df = new DecimalFormat("0.########");
            return df.format(money2);
    }

    /**
     * 截取字符串长度  保留最后两位
     *
     * @param initString
     * @return
     */
    public static String subString2(String initString) {
        double parseDouble = Double.parseDouble(initString);
        DecimalFormat mformat = new DecimalFormat("0.00");
        String format = mformat.format(parseDouble);
        return format;
    }

    /**
     * 截取字符串，保留3位数
     *
     * @param initString
     * @return
     */
    public static String subString3(String initString) {
        double parseDouble = Double.parseDouble(initString);
        DecimalFormat mformat = new DecimalFormat("0.000");
        String format = mformat.format(parseDouble);
        return format;
    }

    public static String doubleSubStringTwo(Double number) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(number);
    }

    public static Double doubleSubStringTwoDouble(Double number) {
        DecimalFormat df = new DecimalFormat("0.00");
        return parseDouble(df.format(number));
    }

    public static double parseDouble(String value) {
        double ret = 0d;

        if (!TextUtils.isEmpty(value)) {
            try {
                ret = Double.parseDouble(value);
            } catch (Exception e) {
            }
        }

        return ret;
    }

    public static int parseInt(String value) {
        int ret = 0;

        if (!TextUtils.isEmpty(value)) {
            try {
                ret = Integer.parseInt(value);
            } catch (Exception e) {
            }
        }

        return ret;
    }

    public static float parseFloat(String value) {
        float ret = 0;
        if (!TextUtils.isEmpty(value)) {
            try {
                ret = Float.parseFloat(value);
            } catch (Exception e) {
            }
        }
        return ret;
    }

    /**
     * @param priceStyle
     * @return 返回价格符号
     */
    @NonNull
    public static String getPriceStyle(String priceStyle) {
        if (TextUtils.isEmpty(priceStyle)) {
            return "";
        }
        int end = priceStyle.indexOf("_");
        String currency = end != -1 ? priceStyle.substring(0, priceStyle.indexOf("_")) : priceStyle;
        if ("usd".equals(currency)) {
            return "＄ ";
        } else if ("btc".equals(currency)) {
            return "฿ ";
        } else if ("jpy".equals(currency)) {
            return "円 ";
        } else if ("krw".equals(currency)) {
            return "₩ ";
        } else if ("euro".equals(currency)) {
            return "€ ";
        } else if ("cny".equals(currency)) {
            return "¥ ";
        } else if ("gbp".equals(currency)) {
            return "£ ";
        }
        return priceStyle.toUpperCase() + " ";
    }

    /**
     * 计算 浮动比率
     *
     * @param last     last  String
     * @param price_24 price_24 String
     * @return
     */
    public static String percentC(String last, String price_24) {
        try {
            double result = Double.parseDouble(last) - Double.parseDouble(price_24);
            double price24 = Double.parseDouble(price_24);
            price24 = price24 == 0 ? 1 : price24;
            double percent = (result) / price24;
            DecimalFormat mformat = new DecimalFormat("0.0000");
            String format1 = mformat.format(percent);
            double parseDouble = Double.parseDouble(format1);
            double v = parseDouble * 100;
            String format = mformat.format(v);
            return subString2(format);
        } catch (Exception e) {
            return "0.00";
        }

    }

    private static String volume_unit1, volume_unit2, volume_unit3;

    public static String longToVolumeHumanReadableFormat(long lNumber, int digit) {
        long tNumber = lNumber;

        if (tNumber < 0) {
            tNumber = Math.abs(lNumber);
        }
        int unit = AppEnv.getLanguage().getUnit();
        int value = 100000;

        if (tNumber < value) {
            return String.valueOf(lNumber);
        }

        if (volume_unit1 == null) {
            volume_unit1 = BaseApp.getApp().getResources().getString(R.string.volume_unit1); // 万
        }

        int exp = (int) (Math.log(tNumber) / Math.log(unit));
        String pre = volume_unit1; // 万
        if (exp == 2) {
            if (volume_unit2 == null) {
                volume_unit2 = BaseApp.getApp().getResources().getString(R.string.volume_unit2); // 亿
            }

            pre = volume_unit2; // 亿
            exp = 2;
        } else if (exp > 2) {
            pre = BaseApp.getApp().getResources().getString(R.string.volume_unit3); //"兆";
            exp = 3;
        }

        double num = tNumber / Math.pow(unit, exp);
        String format = (num * unit % unit) == 0.0 ? "%.0f" : "%." + digit + "f";
        if (lNumber < 0) {
            format = "-" + format;
        }
        return String.format(Locale.ENGLISH, format, num) + pre;
    }
    public static String transformNumberToK(int number){
        final int k = 1000;
        if (number<k){
            return String.valueOf(number);
        }else {
            return CalculateUtil.div(number,k,1)+"k";
        }
    }
    public static String transformNumberToQian(int number){
        final int k = 1000;
        if (number<k){
            return String.valueOf(number);
        }else {
            return CalculateUtil.div(number,k,1)+"千";
        }
    }
    /*
     * 将时间转换为时间戳
     */
    public static String dateToStampHMS(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        int newts = (int) (ts / 1000);
        res = String.valueOf(newts);
        return res;
    }


    public static String dateToStampYMDHM(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        int newts = (int) (ts / 1000);
        res = String.valueOf(newts);
        return res;
    }

    //Long 类型转换成String类型时间
    public static String StringDataToString(String string) {
        int time = Integer.parseInt(string);
        long newTime = time * 1000L;
        Date date = new Date(newTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String str = sdf.format(date);
        return str;
    }

    //Long 类型转换成String类型时间
    public static String StringDataToStringHMS(String string) {
        int time = FormatUtil.parseInt(string);
        long newTime = time * 1000L;
        Date date = new Date(newTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = sdf.format(date);
        return str;
    }

    /**
     * 转换日期格式成为 带有时分秒的
     */
    public static String getTimetoHMS(int time, String pattern) {
        long newTime = time * 1000L;
        Date date = new Date(newTime);
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        return formatter.format(date);
    }

    public static String getTimetoHMS(long time, String pattern) {
        Date date = new Date(time);
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        return formatter.format(date);
    }

    /**
     * 转换日期格式成为 带有时分秒的
     *
     * @param time
     * @return
     */
    public static String getTimetoHMS(int time) {
        return getTimetoHMS(time, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * @param start
     * @param end
     * @return 0 预热中 1，进行中 2，已结束
     */
    public static String getDateStatus(String start, String end) {
        long intStart = 0L;
        long intEnd = 0L;
        long currentTimeMillis = System.currentTimeMillis();
        if (start != null) {
            intStart = parseInt(start) * 1000L;
            if (intStart > currentTimeMillis) {
                return "0";
            }
        }
        if (end != null) {
            intEnd = parseInt(end) * 1000L;
            if (intEnd < currentTimeMillis) {
                return "2";
            }
        }
        if (end != null && start != null) {
            intStart = parseInt(start) * 1000L;
            intEnd = parseInt(end) * 1000L;
            if (intStart < currentTimeMillis && intEnd > currentTimeMillis) {
                return "1";
            }
        }
        return "2";
    }

    public static long parseLong(String value) {
        long ret = 0;

        if (!TextUtils.isEmpty(value)) {
            try {
                ret = Long.parseLong(value);
            } catch (Exception e) {
            }
        }
        return ret;
    }

    /**
     * 10000 -> 10,000 數字加上千位數的逗號
     *
     * @param str
     * @return
     */
    public static String NumberAddComma(String str) {
        if (!TextUtils.isEmpty(str)) {
            try {
                int pos = str.lastIndexOf(".");
                if (pos < 0) {
                    for (int ii = str.length() - 1; ii >= 0; ii--) {
                        if (str.charAt(ii) >= '0' && str.charAt(ii) <= '9') {
                            pos = ii;
                            break;
                        }
                    }
                } else {
                    pos--;
                }

                String aRight = str.substring(pos + 1);
                String aLeft = str.substring(0, pos + 1);
                DecimalFormat format = new DecimalFormat("#,###");
                if (!"-0".equals(aLeft)) {
                    aLeft = format.format(Integer.valueOf(aLeft));
                }

                str = aLeft + aRight;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return str;
    }

    /**
     * 取得價格字串的小數位數
     *
     * @param strData
     * @return 小數位數, 0代表整數
     */
    public static int getDigitNumber(String strData) {
        if (strData.contains("E")) {
            int num = Integer.parseInt(strData.split("E")[1]);
            if (num >= 0) {
                return 0;
            } else {
                int tlength = strData.split("E")[0].length() - 2;
                tlength = tlength + Math.abs(Integer.parseInt(strData.toString().split("E")[1]));
                return tlength;
            }

        }

        int dot = strData.indexOf('.');
        return dot < 0 ? 0 : strData.length() - dot - 1;
    }

    /**
     * 取得指定小數位數的價格字串(超過四捨五入)
     *
     * @param dbValue 價格
     * @param digit   小數位數, 0代表整數
     * @return 價格字串
     */
    public static String getFormatString(double dbValue, int digit) {
        if (digit < 0)
            digit = 2;

        return String.format(Locale.ENGLISH, "%1$." + digit + "f", dbValue);
    }

    //    以下是汇率详情页面的数据转换～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～～

    /**
     * 计算人民币
     *
     * @param buy 字符串形式
     * @param cny double类型
     * @return
     */
    public static String totalMoney(String buy, Double cny) {
        double parseDouble = Double.parseDouble(buy);
        double total = parseDouble * cny;
        DecimalFormat mformat = new DecimalFormat("0.00");
        String format = mformat.format(total);
        return format;

    }

    /**
     * 计算差价 高开低收
     *
     * @param start Price——24 String
     * @param end   last  String
     * @return
     */
    public static String differencePrice(String start, String end) {
        double d_start = Double.parseDouble(start);
        double d_end = Double.parseDouble(end);
        double difference = d_start - d_end;

        DecimalFormat mformat = new DecimalFormat("0.00");
        String format = mformat.format(difference);
        return format;
    }

    public static String differencePriceSigned(String start, String end) {
        double d_start = Double.parseDouble(start);
        double d_end = Double.parseDouble(end);
        double difference = d_start - d_end;


        DecimalFormat mformat = new DecimalFormat("0.00");
        String format = mformat.format(difference);
        if (difference > 0) {
            format = "+" + format;
        }
        return format;
    }

    public static boolean compare(String start, String end) {
        double d_start = Double.parseDouble(start);
        double d_end = Double.parseDouble(end);
        double difference = d_start - d_end;

        if (difference > 0) {
            return true;
        }
        return false;

    }


    public static String percentCSighed(String last, String price_24) {
        double result = Double.parseDouble(last) - Double.parseDouble(price_24);
        double price24 = Double.parseDouble(price_24);
        price24 = price24 == 0 ? 1 : price24;
        double percent = (result) / price24;
        DecimalFormat mformat = new DecimalFormat("0.0000");
        String format1 = mformat.format(percent);
        double parseDouble = Double.parseDouble(format1);
        double v = parseDouble * 100;
        String format = mformat.format(v);
        return result > 0 ? "+" + subString2(format) : subString2(format);
    }


}
